/*
Copyright (c) 2014, Rick Wilson
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of 'Taareekah' nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


import worldgeneration.WorldGenerator;
import world.GenericTerrainMap;
import util.BitmapPixelShader;
import worldgeneration.Util;
import com.jme3.math.FastMath;
import java.util.logging.Level;
import java.util.logging.Logger;
import util.BMPFile;
import javax.xml.parsers.DocumentBuilderFactory;
import util.MeshInterpolator;
import parameters.*;
/**
 *
 * @author rick
 */
    
    public class ClimateZone {
        public name;
        public desc;
        public latituderange = [];
        public temperaturerange = [];
        
        def ClimateZone(node) {
            if (node.nodeName != 'climatezone') return
            name = node.attributes.getNamedItem('name').nodeValue
            
            def latnode = node.getElementsByTagName('latituderange').item(0)
            latituderange = [latnode.attributes.getNamedItem('min').nodeValue.toInteger(), latnode.attributes.getNamedItem('max').nodeValue.toInteger()]
            
            def tempnode = node.getElementsByTagName('temperaturerange').item(0)
            temperaturerange = [tempnode.attributes.getNamedItem('min').nodeValue.toInteger(), tempnode.attributes.getNamedItem('max').nodeValue.toInteger()]
            
            desc = node.getElementsByTagName('description').item(0).firstChild.nodeValue
        }
    }
    public int determineClimateZoneAndAssignTemperatureFloat(float y, Random rand, int size, ClimateZone[] climate_zones) {
        int latitude = Math.round(Math.toDegrees(Util.latitudeNorthHemisphereFloat(y, size)));
        for (x in climate_zones) {
            if (latitude >= x.latituderange[0] && latitude <= x.latituderange[1]) {
                int t_range = Math.abs(x.temperaturerange[1] - x.temperaturerange[0])
                return rand.nextInt(t_range) + x.temperaturerange[0]
            }
        }
        
        return -1;
    }
    int min = (int)globalparameters.getChild("terrain.temperature.min").getValueAsFloat();
    int max = (int)globalparameters.getChild("terrain.temperature.max").getValueAsFloat();
    int mesh = globalparameters.getChild("terrain.temperature.mesh").getValueAsInt();
    
    int size = worldgenerator.getWorldSize();
    long seed = worldgenerator.getSeed();
    
    def loadClimateZoneParams(String filename) {
        def climate_zones = [];
        def builder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
        def records = builder.parse(new FileInputStream(new File(filename))).documentElement
        
        def zones = records.childNodes
        (0..<zones.length).each{ climate_zones.push(new ClimateZone(zones.item(it))) }
        return climate_zones;
    }
    
    def climate_zones = loadClimateZoneParams(scriptparameters.getChild("climatezoneparams").getValueAsString());
    Random rand = new Random(seed);
    class InitialValue extends MeshInterpolator.InitialValueGenerator {
        def climate_zones = [];
        Random rand;
        public InitialValue(climate_zones, Random rand) {
            this.climate_zones = climate_zones;
            this.rand = rand;
        }
        public float getValueAtPoint(int x, int y, int mesh_size, int size) {
            int latitude = Math.round(Math.toDegrees(Util.latitudeNorthHemisphere(y, size + 1)));
            for (i in climate_zones) {
                if (latitude >= i.latituderange[0] && latitude <= i.latituderange[1]) {
                    int t_range = Math.abs(i.temperaturerange[1] - i.temperaturerange[0])
                    return (float)(rand.nextInt(t_range) + i.temperaturerange[0])
                }
            }

            return 0.0f;
        }
    }
    GenericTerrainMap temp_map = MeshInterpolator.perform(new InitialValue(climate_zones, rand), mesh, size);
    temp_map.setIsLoaded(true);

class Shader extends BitmapPixelShader {
    private GenericTerrainMap map;
    public Shader (GenericTerrainMap map) {
        this.map = map;
    }
    public int[] getColorAtPoint(int x, int y) {
        int temp = Math.round(map.getValueAtPoint(x, y) + 40.0);
        int factor = Math.round((255.0 * ((map.getValueAtPoint(x, y) + 40.0).div(100))));
        int[] ret = new int[3];
        ret[0] = ret[1] = ret[2] = 0;
                if (temp < 40) {
                    ret[2] = factor;
                } else if (temp < 75) {
                    ret[1] = factor;
                } else {
                    ret[0] = factor;
                }
        return ret;
    }
}
    boolean saveAsBitmap(String filename, GenericTerrainMap map) throws Exception {
        int size = map.getSize();
        int[] buffer = new int[size * size];
        for (int x = 0; x < size; x++) {
            for (int y = 0; y < size; y++) {
                int temp = Math.round(map.getValueAtPoint(x, y) + 40.0);
                int factor = Math.round((255.0 * ((map.getValueAtPoint(x, y) + 40.0).div(100))));
                byte t;
                if (factor > 127) {
                    t = (byte)(factor - 256);
                } else {
                    t = (byte)factor;
                }
		int pos = map.mapCoordsToBitmapIndex(x, y);
	    
	    
                if (temp < 33) {
                    buffer[pos] = BMPFile.rgbToInt((byte)0, (byte)0, t);
                } else if (temp < 66) {
                    buffer[pos] = BMPFile.rgbToInt((byte)0, t, (byte)0);
                } else {
                    buffer[pos] = BMPFile.rgbToInt(t, (byte)0, (byte)0);
                }
            }
        }
        BMPFile bmp = new BMPFile();
        try {
            bmp.saveBitmap(filename, buffer, size, size);
        } catch (Exception e) {
            throw e;
        }
        
        return true;
    }
temp_map.setShader(new Shader(temp_map));
//saveAsBitmap("temperature.bmp", temp_map);
worldgenerator.setMap("temperature", temp_map);